﻿using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
using ASP;
using Infrastructure.Controls;
using Infrastructure.HardCoding;
using LinQProject;
using ServiceProject;
using ServiceProject.EntityService;
using ServiceProject.VirtualClasses;

public partial class Products : Page
{

    #region Fields (4)
    private static readonly FarmacieDataClassesDataContext database = new FarmacieDataClassesDataContext();
    protected CategoryService categService=new CategoryService(database);
    protected static ProductBussiness prodBussiness=new ProductBussiness(new ProductService(database) );
    //protected ProductCategoryService prodCategService=new ProductCategoryService(database);
    //protected MaintananceBussiness maintBussiness=new MaintananceBussiness(database);
   
    #endregion Fields
   
    protected Products()
    {
        //_3acEcommerceDataContext database = new _3acEcommerceDataContext();
        //maintBussiness = new MaintananceBussiness(database);
        //categService = new CategoryService(database);
        //prodBussiness = new ProductBussiness(new ProductService(database), new ProductDetailService(database));
        //prodCategService = new ProductCategoryService(database);   
    }
    #region Properties (3)

    protected int index
    {
        get
        {
            if (Session["index"] == null)
                return 0;
            return (int)Session["index"];
        }
        set
        {
            Session["index"] = value;
        }
    }

    public int ProductCategoryId
    {
        get
        {
            int intValue;
            if (Int32.TryParse(hdnCategory.Value, out intValue))
                return intValue;

            return 1;
        }
        set { hdnCategory.Value = value.ToString(); }
    }

    protected IDictionary<string, SelectedProduct> SelectionForCos
    {
        get
        {
            if (Session["SelectionForCos"] == null)
                return new Dictionary<string, SelectedProduct>();
            return (IDictionary<string, SelectedProduct>)Session["SelectionForCos"];
        }
        set
        {
            Session["SelectionForCos"] = value;
        }
    }

    protected IDictionary<string, SelectedProduct> SelectionForRequest
    {
        get
        {
            if (Session["SelectionForRequest"] == null)
                return new Dictionary<string, SelectedProduct>();
            return (IDictionary<string, SelectedProduct>)Session["SelectionForRequest"];
        }
        set
        {
            Session["SelectionForRequest"] = value;
        }
    }
    #endregion Properties

    #region Methods (6)


    // Protected Methods (4) 

    protected void lnkCos_Click(object sender, EventArgs e)
    {
        int materialId;
        int productId;
        int materialColourId;
        int productQuantity;
        decimal productPrice;
        bool toProcess = ProcessOrder(sender,  out productId, out productQuantity, out productPrice);
        if (toProcess)
        {
            AddTo(SelectionForCos, productId, productQuantity, productPrice,true);
        }
    }

    private void AddTo(  IDictionary<string, SelectedProduct> Selection,
                                int productId, 
                                int productQuantity, 
                                decimal productPrice,
                                bool isCos)
    {
        //string materialColour = materialColourId == 0 ? "null" : materialColourId.ToString();
        string keyToFind = string.Format("{0}", productId);
        if (Selection.ContainsKey(keyToFind))
            Selection[keyToFind].ProductQuantity = productQuantity;
        else
            Selection.Add(keyToFind,
                                new SelectedProduct(productId,productPrice,
                                                    productQuantity));
        if (isCos)
            SelectionForCos = Selection;
        else
            SelectionForRequest = Selection;

        Control selCos = isCos ? Page.Master.FindControl("selCos") : Page.Master.FindControl("selCerere");
        controls_ucselection_ascx ucSelCos = selCos as controls_ucselection_ascx;
        if (ucSelCos != null)
        {
            ucSelCos.Selection = Selection;
            //Session["Selection"] = Selection;
            ucSelCos.LoadRepeater();
        }

    }

    private bool ProcessOrder(object sender, out int productId, out int productQuantity, out decimal productPrice)
    {
        LinkButton lnk = (LinkButton)sender;
        int indexButton = Convert.ToInt32(lnk.CommandArgument);

      
        productId = 0;
       productQuantity = 0;
        productPrice = 0m;
        ucProduct ucproduct = (ucProduct)gridProducts.Rows[indexButton].FindControl("ucProduct");
        //
        Label lblerror = (Label)ucproduct.FindControl("lblError");
        if (lblerror == null)
            return false;
        //
        //DropDownList ddlmaterial = (DropDownList)ucproduct.FindControl("ddlMaterial");
        //if (ddlmaterial == null)
        //    return false;
        //materialId = Convert.ToInt32(ddlmaterial.SelectedValue);
        //if (materialId == 0)
        //{
        //    Display.DisplayMessages(lblerror, Message.noMaterial, true);
        //    return false;
        //}
        Display.DisplayMessages(lblerror, string.Empty, false);
        //
        productId = ucproduct.ProductId;
        //
        //DropDownList ddlColourMaterial = (DropDownList)ucproduct.FindControl("ddlColour");
        //materialColourId = 0;
        //if (ddlColourMaterial == null)
        //    return false;
        //if (ddlColourMaterial.Items.Count > 0)
        //{
        //    materialColourId = Convert.ToInt32(ddlColourMaterial.SelectedValue);
        //    if (materialColourId == 0)
        //    {
        //        Display.DisplayMessages(lblerror, Message.noColour, true);
        //        return false;
        //    }
        //    Display.DisplayMessages(lblerror, string.Empty, false);
        //}
        //
        TextBox txtQuantity = (TextBox)ucproduct.FindControl("txtCant");
        if (txtQuantity == null)
            return false;
        if (String.IsNullOrEmpty(txtQuantity.Text))
        {
            Display.DisplayMessages(lblerror, Message.noQuantity, true);
            return false;
        }
        Display.DisplayMessages(lblerror, string.Empty, false);
        productQuantity = Convert.ToInt32(txtQuantity.Text);
        if (productQuantity == 0)
        {
            Display.DisplayMessages(lblerror, Message.noQuantity, true);
            return false;
        }
        Display.DisplayMessages(lblerror, string.Empty, false);
        //
        TextBox txtPrice = (TextBox)ucproduct.FindControl("txtPrice");
        if (txtPrice == null)
            return false;
        
        decimal result;
        //if (Convert.ToInt32(maintBussiness.GetSetting((int)Enums.settings.productOfDayId).SetariValue) == productId && Decimal.TryParse(GetSetting(), out result))
        //    productPrice = Convert.ToDecimal(txtPrice.Text)*(100 - result)/100;    
        //else
            productPrice = Convert.ToDecimal(txtPrice.Text);
        return true;
        
       // productPrice = Convert.ToDecimal(txtPrice.Text);
        //return true;
    }

    private string GetSetting()
    {
        const int settingId = (int)Enums.settings.discountProduct;
        //Setting sett = maintBussiness.GetSetting(settingId);
        //if (sett == null)
        //    return string.Empty;
        //return sett.SetariValue;
        return string.Empty;
    }

    protected void Page_Load(object sender, EventArgs e)
    {
      if (!IsPostBack)
        {
            if (Request.QueryString["categoryId"] != null)
            {
                int result;
                if (Int32.TryParse((Request.QueryString["categoryId"]),out result))
                    ProductCategoryId = result;
            }
            //LoadTree();
            LoadGrid(ProductCategoryId, 0);

        }
    }

    //protected void repeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
    //{
    //    if (e.Item == null)
    //        return;
    //    if (e.Item.ItemIndex > -1)
    //    {
    //        ucproduct_ascx ucProd = (ucproduct_ascx)e.Item.FindControl("ucProduct");
    //        if (ucProd != null)
    //        {
    //            ucProd.ProductId = ((Product)(e.Item.DataItem)).ProductId;
    //            ucProd.LoadObjects();
    //            ucProd.Index = e.Item.ItemIndex;
    //        }

    //        LinkButton lnkcos = (LinkButton)e.Item.FindControl("lnkCos");
    //        if (lnkcos != null)
    //            lnkcos.CommandArgument = e.Item.ItemIndex.ToString();
            
    //        LinkButton lnkcerere = (LinkButton)e.Item.FindControl("lnkCerere");
    //        if (lnkcerere != null)
    //            lnkcerere.CommandArgument = e.Item.ItemIndex.ToString();

    //    }
    //}


    protected void TreeViewMeniu_SelectedNodeChanged(object sender, EventArgs e)
    {
        ////this.TreeViewMeniu.CollapseAll();
        //TreeViewMeniu.SelectedNode.Expand();
        //if (TreeViewMeniu.SelectedNode.Depth == (int)Enums.enumNodeDepth.lastNode)
        //{
        //    ProductCategoryId = Convert.ToInt32(TreeViewMeniu.SelectedNode.Value);
        //    LoadGrid(ProductCategoryId, 0);
        //    lblselectedNode.Text = TreeViewMeniu.SelectedNode.Text;
        //}
    }

    // Private Methods (2) 

    private void LoadGrid(int productCategoryId, int pageIndex)
    {
        IList<Product> listaproduse = prodBussiness.GetProductsByProductCategory(productCategoryId);
        if (listaproduse == null)
            return;
        gridProducts.DataSource = listaproduse;
        gridProducts.PageIndex = pageIndex;
        gridProducts.DataBind();
        lblselectedNode.Text = string.Empty;
            //listaproduse[0].ProductCategory.ProductCategoryName;

    }

    //private void LoadTree()
    //{
    //    TreeViewMeniu.Nodes.Clear();

    //    List<Category> listaCategory = (List<Category>)categService.GetAllActiveCategory();
    //    foreach (Category c in listaCategory)
    //    {
    //        TreeNode tnm = new TreeNode(c.categoryName, c.categoryId.ToString());
    //        TreeViewMeniu.Nodes.Add(tnm);

    //        //List<ProductCategory> listaProductCategory = (List<ProductCategory>)prodCategService.GetAllActiveCategoryByCategory(c.CategoryId);
    //        //foreach (ProductCategory pc in listaProductCategory)
    //        //{
    //        //    TreeNode tng = new TreeNode(pc.ProductCategoryName, pc.ProductCategoryId.ToString());
    //        //    tnm.ChildNodes.Add(tng);
    //        //}//end foreach grupe
    //    }//end foreach module
    //}


    #endregion Methods

    protected void lnkCerere_Click(object sender, EventArgs e)
    {
        int materialId;
        int productId;
        int materialColourId;
        int productQuantity;
        decimal productPrice;

        bool toProcess = ProcessOrder(sender,out productId, 
                                              out productQuantity, out productPrice);
        if (toProcess)
        {
            AddTo(SelectionForRequest, productId, productQuantity, productPrice, false);
        }
    }

    protected void gridProducts_pageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gridProducts.PageIndex = e.NewPageIndex;
        int pageIndex = gridProducts.PageIndex;
        LoadGrid(ProductCategoryId, pageIndex);
    }

   protected void gridProducts_rowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            if (e.Row.DataItemIndex >= gridProducts.PageIndex * gridProducts.PageSize
                && (e.Row.DataItemIndex <= (gridProducts.PageIndex + 1) * gridProducts.PageSize))
            {
                ucproduct_ascx ucProd = (ucproduct_ascx)e.Row.FindControl("ucProduct");
                if (ucProd != null)
                {
                    ucProd.ProductId = ((Product)(e.Row.DataItem)).ProductId;
                    ucProd.LoadObjects();
                    ucProd.Index = e.Row.RowIndex;
                }

                LinkButton lnkcos = (LinkButton)e.Row.FindControl("lnkCos");
                if (lnkcos != null)
                    lnkcos.CommandArgument = e.Row.RowIndex.ToString();

                LinkButton lnkcerere = (LinkButton)e.Row.FindControl("lnkCerere");
                if (lnkcerere != null)
                    lnkcerere.CommandArgument = e.Row.RowIndex.ToString();
            }
        }
    }
}
